import React from "react";
import { Form, Button, Input, Select } from "antd";
import { FormComponentProps } from "antd/lib/form/Form"; //获取Form表单的interface
import { FormItemProps } from "antd/lib/form/FormItem";
import { FromField } from "../../utils/interface";

import { StandardFromProps } from "../../utils/interface";

/**
 * 动态表单渲染
 */

const FormItem = Form.Item;

const { Option } = Select;

interface IStates {}

const formItemLayout: FormItemProps = {
	labelCol: {
		xs: {
			span: 24,
		},
		sm: {
			span: 2,
		},
	},
	wrapperCol: {
		xs: {
			span: 24,
		},
		sm: {
			span: 4,
		},
	},
};

/**
 * Option value key 必须为唯一值
 *
 * @param {Array<any>} optionLists
 * @returns
 */
function getSelectOption(optionLists: Array<any>) {
	if (!optionLists) {
		return [];
	}
	let list: Array<any> = [
		<Option value="0" key="0">
			全部
		</Option>,
	];
	optionLists.forEach((item) => {
		let option = (
			<Option value={item.value} key={item.key}>
				{item.label}
			</Option>
		);
		list.push(option);
	});

	return list;
}

class StandardFrom extends React.Component<StandardFromProps, IStates> {
	constructor(props: StandardFromProps, state: IStates) {
		super(props, state);
		this.state = {};
	}

	getFormList() {
		const { getFieldDecorator } = this.props.form;

		let formList = this.props.formList;

		let formDom: Array<any> = [];

		if (!formList) {
			return [];
		}

		formList.forEach((item: FromField) => {
			switch (item.type) {
				case "input":
					let inputForm = (
						<FormItem label={item.label} key={item.key} {...formItemLayout}>
							{getFieldDecorator(item.field, {
								initialValue: item.initialValue,
								rules: item.rules,
							})(<Input type="text" style={{ width: `${item.width}px` }} placeholder={item.placeholder} />)}
						</FormItem>
					);
					formDom.push(inputForm);
					break;

				case "select":
					let selectForm = (
						<FormItem label={item.label} key={item.key} {...formItemLayout}>
							{getFieldDecorator(item.field, {
								initialValue: item.initialValue,
								rules: item.rules,
							})(
								<Select style={{ width: `${item.width}px` }} placeholder={item.placeholder}>
									{getSelectOption(item.optionLists)}
								</Select>
							)}
						</FormItem>
					);
					formDom.push(selectForm);
					break;
				default:
					break;
			}
		});

		return formDom;
	}

	render() {
		return (
			<div>
				<Form layout="inline">
					{this.getFormList()}
					<FormItem>
						<Button type="primary" onClick={this.props.handleSubmit}>
							提交
						</Button>
						<Button type="default">重置</Button>
					</FormItem>
				</Form>
			</div>
		);
	}
}

export default StandardFrom;
